<?php defined('SYSPATH') or die('No direct script access.');
/**
 * KindEditor Controller
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: kindeditor.php 1 2014-01-13 15:05:51Z zhouyl $
 */
class Controller_Admin_Kindeditor extends Kohana_Controller
{

    /**
     * 定义允许上传的文件扩展名
     *
     * @var array
     */
    protected $_exts =  array(
        'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
        'flash' => array('swf', 'flv'),
        'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
        'file'  => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
    );

    /**
     * 文件存储目录
     *
     * @var string
     */
    protected $_savepath = 'editor';

    /**
     * Upload Action
     */
    public function action_upload()
    {
        try
        {
            if ( ! Manager::instance()->is_logined())
            {
                throw new Kohana_Exception('权限不足');
            }

            $dir = Arr::get($_GET, 'dir');

            if ( ! isset($this->_exts[$dir]))
            {
                throw new Kohana_Exception('无效的上传目录 ":dir"',
                    array(':dir' => $dir));
            }

            $exts = $this->_exts[$dir];
            if ($dir == 'file')
            {
                $exts = array_merge($exts, $this->_exts['image'], $this->_exts['flash'], $this->_exts['media']);
            }

            // 存储路径
            $savepath = '/'.$this->_savepath.'/'.$dir;

            // 上传配置
            $config = array(
                'exts'   => $exts,
                'size'   => 4096, // 最大文件上传尺寸 (KB)，默认为 4MB
                'path'   => UPDPATH.$savepath,
                'rename' => 'editor'
            );

            // 执行上传
            $result = Upload::factory($config)->save((array) Arr::get($_FILES, 'upfile'));

            // 文件地址
            $file = ltrim(str_replace('\\', '/', $result['file']), '/');

            // 构造响应数据
            $data = array('error' => 0, 'url' => URL::resource($savepath.'/'.$file));
        }
        catch (Exception $e)
        {
            $data = array('error' => 1, 'message' => $e->getMessage());
        }

        exit(JSON::encode($data, FALSE));
    }

    /**
     * File Manager Action
     */
    public function action_filemanager()
    {
        try
        {
            if ( ! Manager::instance()->is_logined())
            {
                throw new Kohana_Exception('权限不足');
            }

            $dir = Arr::get($_GET, 'dir', 'image');

            if ( ! isset($this->_exts[$dir]))
            {
                throw new Kohana_Exception('无效的上传目录 ":dir"',
                    array(':dir' => $dir));
            }

            // 存储路径
            $savepath = '/'.$this->_savepath.'/'.$dir;

            // 根路径
            $root_path = IO::mkdir(UPDPATH.$savepath);

            // 基础 URL
            $base_url = URL::resource($savepath);

            $path = Arr::get($_GET, 'path', '');

            $current_path = $root_path.'/'.$path;
            $current_url = $base_url.'/'.$path;
            $current_dir_path = ltrim($path, '/').'/';
            $moveup_dir_path = ltrim(dirname($current_dir_path), '.');

            // 目录不存在或不是目录
            if ( ! is_dir($current_path))
            {
                throw new Kohana_Exception('目录不存在 ":path"', array(':path' => $path));
            }

            $file_list = array();

            foreach (new DirectoryIterator($current_path) as $dir)
            {
                $filename = $dir->getFilename();

                if ($filename{0} == '.')
                {
                    continue;
                }

                $ext = strtolower(substr(strrchr($filename, '.'), 1));
                $file_list[] = array(
                    'is_dir'   => $dir->isDir(),
                    'has_file' => IO::is_empty_dir($dir->getRealPath()),
                    'filesize' => $dir->getSize(),
                    'dir_path' => '',
                    'is_photo' => in_array($ext, $this->_exts['image']),
                    'filetype' => $ext,
                    'filename' => $filename,
                    'datetime' => date('Y-m-d H:i:s', $dir->getMTime()),
                );
            }

            // 执行排序
            usort($file_list, array($this, '_cmp_files'));

            $result = array(
                'moveup_dir_path'  => $moveup_dir_path,  // 相对于根目录的上一级目录
                'current_dir_path' => $current_dir_path, // 相对于根目录的当前目录
                'current_url'      => $current_url,      // 当前目录的URL
                'total_count'      => count($file_list), // 文件数
                'file_list'        => $file_list,        // 文件列表数组
            );

            exit(JSON::encode($result, TRUE));
        }
        catch (Exception $e)
        {
            exit(JSON::encode(array('message' => $e->getMessage()), TRUE));
        }

    }

    /**
     * 对文件列表进行排序
     *
     * @param  array  $a
     * @param  array  $b
     * @return int
     */
    protected function _cmp_files($a, $b)
    {
        $order = strtolower(Arr::get($_GET, 'order'));
        in_array($order, array('name', 'type', 'size')) OR $order = 'name';

        if ($a['is_dir'] AND ! $b['is_dir'])
            return -1;

        if ( ! $a['is_dir'] AND $b['is_dir'])
            return 1;

        if ($order == 'name')
            return strcmp($a['filename'], $b['filename']);

        if ($order == 'type')
            return strcmp($a['filetype'], $b['filetype']);

        if ($a['filesize'] > $b['filesize'])
            return 1;

        if ($a['filesize'] < $b['filesize'])
            return -1;

        return 0;
    }

}